#pragma once

#include <iostream>
#include "Protocol.hpp"

enum
{
    Div_Zero = 1,
    MOD_Zero,
    Other_oper
};

class ServerCal
{
public:
    ServerCal() {}
    ~ServerCal() {}
    Response CalculatorHelper(const Request &req)
    {
        Response resp(0, 0);
        switch (req.m_op)
        {
        case '+':
            resp.m_result = req.m_data1 + req.m_data2;
            break;
        case '-':
            resp.m_result = req.m_data1 - req.m_data2;
            break;
        case '*':
            resp.m_result = req.m_data1 * req.m_data2;
            break;
        case '/':
        {
            if (req.m_data2 == 0)
                resp.m_exitcode = Div_Zero;
            else
                resp.m_result = req.m_data1 / req.m_data2;
        }
        break;
        case '%':
        {
            if (req.m_data2 == 0)
                resp.m_exitcode = MOD_Zero;
            else
                resp.m_result = req.m_data1 % req.m_data2;
        }
        break;
        default:
            resp.m_exitcode = Other_oper;
            break;
        }

        return resp; // 返回时调用自己的拷贝构造
    }

    std::string Calculator(std::string &package)
    {
        std::string content;
        bool ret = Decode(package, &content); //"len\n10 + 20\n"
        if (!ret)
            return "";
        // "10 + 20"
        Request req;
        ret = req.Deserialize(content); // "10 + 20" => m_data1 = 10, m_data2 = 20, m_op = +
        if (!ret)
            return "";

        content = "";
        Response resp = CalculatorHelper(req); // m_result = 30, m_exitcode = 0
        resp.Serialize(&content);              // "30 0"
        content = Encode(content);             // "len\n30 0\n"

        return content;
    }

public:
};